package com.webdrop.gui;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.storage.client.Storage;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.webdrop.client.UrlToServer;

public class Header extends Composite{
	
	HorizontalPanel header; 
	Storage sessionStorage;
	Button logoutButton;
	Button uploadButton;
	HorizontalPanel logoutPanel;
	
	UrlToServer urlToServer = new UrlToServer();
	
	ViewFilesTab viewFilesTab;
	
	public Header(ViewFilesTab viewFilesTab){

		this.viewFilesTab = viewFilesTab;
		sessionStorage=Storage.getSessionStorageIfSupported();
		logoutPanel = new HorizontalPanel();
		header = new HorizontalPanel();
		header.addStyleName("header");
		header.setTitle("WebDrop");
		
		// WebDrop header
		Image logo = new Image("img/logo.png");
		header.add(logo);

		logoutButton = new Button("Logout");
		uploadButton = new Button("Upload new files");
		
		// btton to upload new files
		uploadButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				String winUrl = "upload.html";
				String winName = "Testing Window";

				openNewWindow(winName, winUrl);  /* spawn a new window - not popup */
				
			}
		});
		
		// Button to logout
		logoutButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				
				String googleId = sessionStorage.getItem("googleId");
				
				if(sessionStorage!=null){
					sessionStorage.clear();
				}
				
				Window.Location.assign(urlToServer.getUrlToServer()+"logout.php?googleId=" + googleId );
				
			}
		});
		logoutPanel.setStyleName("nextimgpanel");
		logoutPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
	
		initWidget(header);

	}
	
	// open a new window
	public static void openNewWindow(String name, String url) {
	    com.google.gwt.user.client.Window.open(url, name.replace(" ", "_"),
	           "menubar=no," + 
	           "location=false," + 
	           "resizable=no," + 
	           "scrollbars=no," +
	           "height=340px," + 
	           "width=640px," + 
	           "status=no," + 
	           "dependent=true");
	}
	
	
	public void onLoad()
	{
		super.onLoad();
		header.setVisible(true);
		VerticalPanel hp = new VerticalPanel();
		Label name = new Label("Logged in as: "+sessionStorage.getItem("userid"));

		name.addStyleName("name");
		logoutPanel.add(logoutButton);
		
		hp.add(name);
		
		header.add(hp);
		header.add(uploadButton);
		header.add(logoutPanel);
	}
}	